package com.lyn.serialPort;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 串口工厂
 *
 * @author Lyn 2022/12/24
 * @version 1.0.0
 */
public class SerialPortFactory {

    private static final Map<String, Port> portMap = new ConcurrentHashMap<>();

    /**
     * 获取串口
     *
     * @param name     串口名称
     * @return Port
     */
    public static Port get(String name) {
        Port port = portMap.get(name);
        if (port != null) {
            return port;
        }
        SerialPort serialPort = new SerialPort();
        portMap.put(name,serialPort);
        return serialPort;
    }

    /**
     * 关闭串口
     *
     * @param name 串口名称
     * @return true关闭成功 false关闭失败
     */
    public static boolean remove(String name) {
        Port port = portMap.get(name);
        if (port == null) {
            return false;
        }
        boolean close = port.close();
        portMap.remove(name);
        return close;
    }

    /**
     * 获取所有串口名称
     *
     * @return 串口名称集合
     */
    public List<String> getAllNames() {
        List<String> stringList = new ArrayList<>();
        List<Device> deviceList = SerialPortFinder.getDevices();
        for (Device device : deviceList) {
            stringList.add(device.name);
        }
        return stringList;
    }

}
